// pages/userInfoCenter/index.js
const App = getApp();
const { Dialog, Toast } = require("../../../../config/modal")
const utils = require("../../../../utils/util")
const { LOGIN, LOCATION } = require("../../../../config/login.js")
Page({
    /**
     * 页面的初始数据
     */
    data: {
        location_icon: '/static/img/school_location.png',
        title: "校园动态",
        showComment: false,
        srcolltop: false,
        showSonComment: false,
        isAuth: App.$isAuth(),
        userIcon: '/static/img/student.png',
        adminIcon: '/static/img/official3.png',
        imgWidth: 110,
        offsetTop: App.globalData.window.navHeight,
        window: App.globalData.window,
        theamTextColor: App.globalData.theamTextColor,
        commentInput: false,
        loadMore: {
            show: false,
            type: "loading",
            text: "加载中..."
        },
        // 用户和地址信息
        location: {},
        // 文章相关数据
        article: {
            mapTabValue: {
                0: [],
                1: [],
                2: [],
                3: []
            },
            list: [],
            activeKey: 0,
            tabs: [
                {
                    name: '推荐',
                    type: "recommend",
                    disabled: false
                },
                {
                    name: '同城',
                    type: "sameCity",
                    disabled: false
                }, {
                    name: '官方动态',
                    type: "official",
                    disabled: false
                }, {
                    name: '我的',
                    type: "mine",
                    disabled: false
                }
            ],
            comment: {
                allCount: 0,
                list: [],
                showSon: [],
                page: {
                    one: 1,
                    pageNum: 1,
                    pageSize: 15,
                    pages: 0,
                    total: 0,
                },
                commentValue: '',
                current: null, // 点击回复的那条评论
                article: {},   // 评论的文章
                articleIndex: 0,   // 评论的文章
                parentId: 0,  // 子级评论的顶级父id
                index: 0,  // 回复的那条数据的下标
                type: '', // 当前条评论的回复类型：parent:回复一级平路，son:回复二级评论 用于评论后直接插入集合中不刷新
                contentPlaceholder: "留下你的评论吧"
            },
        },

        // 搜索参数
        searchParams: {
            type: '',
            city: '',
        },

        getCommentSonParentId: '',
        page: {
            one: 1,
            pageNum: 1,
            pageSize: 15,
            pages: 0,
        },
        startDongTai: App.$getActionFlag(),
        // 初始化tab,用于记录点击过后的tab,目的是让其切换来去，不进行更新数据
        initedTab: [],
    },
    URL: {
        getList: "/article/pageList",
        progress: "/user/integral/goods/getProgress/?",
        tabType: "/article/tabType",
        agree: "/article/agree/?",
        delete: "/article/delete/?",
        commentList: "/comment/list",
        listSon: "/comment/listSon",
        comment: '/comment/insertSave/reply',
        support: "/comment/support/?",
        deleteComment: "/comment/delete/?",
        getMyInfo: "/customer/getMyInfo",
        getAllCountNum: "/comment/getAllCountNum/?",
    },
    page: {
        progress: "/pages/tabbar/user/integral/progress/index",
        GoodsDetail: "/pages/tabbar/user/integral/exchange/goods-detail/index",
        noAuth: "/pages/noAuth/index",
        pushArticle: "/pages/tabbar/dynamic/pushArticle/index",
        target: "/pages/tabbar/dynamic/list/index",

    },

    // 计算图片的宽度 让其均等占屏幕等分
    computeImgWidth() {
        this.setData({
            'imgWidth': ((this.data.window.windowWidth - (3 * 10)) - (750 / this.data.window.windowWidth) * 30) / 3
        })
    },


    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        App.$handlerInviteCode(options);
        this.computeImgWidth();
        this.tabTypeInit();
        this.initTabData(options);
        this.setData({
            startDongTai: App.$getActionFlag()
        })
    },

    initTabData(options) {
        let initType = 1;
        if (!utils.isInvalid(options.type)) {
            initType = options.type;
        }
        this.init(initType, false, this.data.article.activeKey);
    },
    onShow() {
        this.setData({
            'isAuth': App.$isAuth(),
            'location': App.$getUserInfo(),
        })
        this.authLocationBackLoad();
    },

    // 进入授权的时候，返回来更新地址
    authLocationBackLoad() {
        if (this.data.article.tabs[this.data.article.activeKey].type == "sameCity") {
            LOCATION.allowed((res => {
                wx.hideLoading();
                if (res) {
                    this.setData({
                        'location': App.$getUserInfo(),
                        'searchParams.city': App.$getUserInfo().citySure,
                    });
                    this.onPullDownRefresh();
                }
            }));
        }
    }

    // 点击更新地理位置信息
    , reloadLocation() {
        LOCATION.toAuthLocation(res => {
            this.setData({
                'location': res
            })
        })
    }

    // 获取tab栏列表
    , tabTypeInit() {
        App.$get(true, this.URL.tabType, {}, res => {
            if (res.R) {
                this.setData({
                    "article.tabs": res.data
                })
            }
        })
    },

    // 初始化数据
    init(pageNum, loadMore, tabKey) {
        let params = this.data.searchParams;
        params['pageNum'] = pageNum
        params['pageSize'] = this.data.page.pageSize
        this.recordingClickTab(tabKey);

        // 上拉到底的时候进行显示加载中
        this.setLoadingMore(loadMore, "loading", "加载中...")

        if (!loadMore ? true : loadMore) {
            // 弹出loading
            wx.showLoading({
                title: '加载中',
                mask: true,
            })
        }

        App.$get(!loadMore ? true : loadMore, this.URL.getList, params, res => {
            wx.stopPullDownRefresh();
            this.setData({
                "loadMore.show": false,
            })
            if (res.R) {
                this.setData({
                    "page.pageNum": res.data.pageNum,
                    "page.pageSize": res.data.pageSize,
                    "page.pages": res.data.pages
                })
                let newData = res.data.rows;
                let sourceData = this.data.article.list;
                if (!loadMore) {
                    sourceData = newData;
                } else {
                    // 上啦刷新，列表追加数据
                    newData.forEach(data => {
                        sourceData.push(data);
                    })
                }
                let mapTabValue = 'article.mapTabValue[' + tabKey + ']';
                this.setData({
                    "article.list": sourceData,
                    [mapTabValue]: sourceData,
                })
            }

            if (!loadMore ? true : loadMore) {
                setTimeout(() => {
                    wx.hideLoading();
                }, 500)
            }
        })
    },

    // tab栏切换
    onTypeChange(event) {
        let index = event.detail.index;
        let data = this.data.article.tabs;
        this.setData({
            'article.activeKey': index,
            'searchParams.type': data[index].type,
        })
        if (data[index].type === "sameCity") {
            // 检查授权
            if (!LOCATION.isAllowedLocation()) {
                LOCATION.toAuthLocation((res => {
                    this.setData({
                        'location': App.$getUserInfo(),
                        'searchParams.city': App.$getUserInfo().citySure,
                    })
                    this.onPullDownRefresh();
                }))
                return;
            } else {
                this.setData({
                    'searchParams.city': this.data.location.citySure,
                })
            }

        } else if (data[index].type === "mine") {
            // 我的 需要校验登陆权限
            if (!LOGIN.isAuthLogin()) {

                App.$on("authedCallback", this, res => {
                    let tag = res.fromParams.tag;
                    if (!utils.isInvalid(tag)) {
                        this.setData({
                            'searchParams.openid': res.userInfo.miniOpenId,
                            'isAuth': true,
                        });
                        this.onPullDownRefresh();
                    }
                });

                // 带一个参数过去授权，授权成功后，回来这个页面的我选项这里
                App.$navigateToAuth({ tag: 'mine' })
                return;
            } else {
                let user = App.$getUserInfo();
                this.setData({
                    'searchParams.openid': user.miniOpenId
                })
            }
        } else {

            this.setData({
                'searchParams.city': '',
                'searchParams.openid': '',
            })
        }
        this.setLoadingMore(false, "", "");

        // 第一页开始
        this.setData({
            'page.pageNum': this.data.page.one,
        })

        // 没点击过的tab
        if (this.data.initedTab.indexOf(index) < 0) {
            this.init(this.data.page.one, false, index)
        }
    }

    // 记录点击过的tab栏 再次点击的时候，不让他刷新
    , recordingClickTab(index) {
        if (this.data.initedTab.indexOf(index) < 0) {
            let tabed = this.data.initedTab;
            tabed.push(index);
            this.setData({
                'initedTab': tabed
            })
        }
    }

    // 点击纸飞机-文章发布
    , btnPlaneClick() {
        if (!LOGIN.isAuthLogin()) {

            // 带一个参数过去授权，授权成功后，回来这个页面的我选项这里
            App.$navigateToAuth({ tag: 'mine_push' })
            App.$on("authedCallback", this, res => {
                let tag = res.fromParams.tag;
                if (!utils.isInvalid(tag) && tag == 'mine_push') {
                    setTimeout(() => {
                        let schoolName = res.userInfo.schoolName;
                        if (utils.isInvalid(schoolName)) {
                            App.$alertConfirm({
                                msg: '发布信息需要先完善资料哦～',
                                success: function () {
                                    App.$navigateTo('/pages/tabbar/user/userInfoEdit/index', true);
                                }
                            })
                            return;
                        }
                        App.$navigateTo(this.page.pushArticle, true)
                    }, 300);
                }
            });
            return;
        }

        let schoolName = App.$getUserInfo().schoolName;
        if (utils.isInvalid(schoolName)) {
            App.$alertConfirm({
                msg: '发布信息需要先完善资料哦～',
                success: function () {
                    App.$navigateTo('/pages/tabbar/user/userInfoEdit/index', true);
                }
            })
            return;
        }
        App.$navigateTo(this.page.pushArticle, true);
    }

    // 删除自己的文章
    , deleteArticle(e) {
        if (e.detail === "right") {
            let item = e.currentTarget.dataset.item;
            let index = e.currentTarget.dataset.index;
            App.$delete(true, this.URL.delete.replace("?", item.articleNo), {}, res => {
                if (res.R) {
                    let list = this.data.article.mapTabValue[this.data.article.activeKey];
                    list.splice(index, 1);
                    let key = 'article.mapTabValue[' + this.data.article.activeKey + ']';
                    this.setData({
                        [key]: list
                    })
                }
            })
        }
    }

    // 文章点赞
    , agree(e) {
        let item = e.currentTarget.dataset.item;
        let index = e.currentTarget.dataset.index;
        let type = e.currentTarget.dataset.type;
        let agreeCount = item.agreeCount + 1;

        let isAgree = item.isAgree;
        if (isAgree) {
            Toast('已经点赞')
            return;
        }

        App.$post(false, this.URL.agree.replace("?", item.articleNo), {}, res => {
            if (res.R) {
                // 修改状态
                let list = this.data.article.mapTabValue[this.data.article.activeKey];
                let keyAgree = 'article.mapTabValue[' + this.data.article.activeKey + '][' + index + '].isAgree'
                let keyAgreeCount = 'article.mapTabValue[' + this.data.article.activeKey + '][' + index + '].agreeCount'
                this.setData({
                    [keyAgree]: true,
                    [keyAgreeCount]: agreeCount
                })
            }
        })
    }



    // 图片放大
    , showLagerImg(e) {
        let imgUrl = e.currentTarget.dataset.img;
        let imgUrls = e.currentTarget.dataset.imgs;
        wx.previewImage({
            current: imgUrl,
            urls: imgUrls
        })
    }

    //--------------------------------------- 评论相关 --------------------------------------//


    // 删除评论
    , deleteComment(e) {
        let indexArr = e.currentTarget.dataset.index.split("");
        let item = e.currentTarget.dataset.item;
        let type = e.currentTarget.dataset.type;
        App.$delete(true, this.URL.deleteComment.replace("?", item.commentNo), {}, res => {
            if (res.R) {
                item['deleted'] = 1;
                item['content'] = '-';
                item['userName'] = '-';
                item['isMe'] = false;
                let itemKey = 'article.comment.list[' + indexArr[0] + '].son[' + indexArr[1] + ']';
                if (type === 'son') {
                    this.setData({
                        [itemKey]: item,
                    })
                    return;
                }
                itemKey = 'article.comment.list[' + indexArr[0] + ']';
                this.setData({
                    [itemKey]: item,
                })
            }
        })
    }


    // 获取评论列表
    , getCommentList(articleNo) {
        App.$get(true, this.URL.commentList, { 'articleNo': articleNo }, res => {
            if (res.R) {
                this.setData({
                    'article.comment.list': res.data.rows,
                    'article.comment.page.total': res.data.total,
                    'article.comment.page.pageNum': res.data.pageNum,
                    'article.comment.page.pages': res.data.pages,
                })
            }
        })
    },

    /**
     * 获取总评论数量
     */
    getAllCountNum(articleNo) {
        App.$get(true, this.URL.getAllCountNum.replace("?", articleNo), {}, res => {
            if (res.R) {
                this.setData({
                    'article.comment.allCount': res.data,
                })
            }
        })
    },


    // 展示更多评论
    showMoreComment() {
        let params = {
            'articleNo': this.data.article.comment.article.articleNo,
            pageNum: this.data.article.comment.page.pageNum + 1
        };
        App.$get(true, this.URL.commentList, params, res => {
            if (res.R) {

                let list = this.data.article.comment.list;
                let data = res.data.rows;
                data.forEach(d => {
                    list.push(d);
                })

                this.setData({
                    'article.comment.list': list,
                    'article.comment.page.total': res.data.total,
                    'article.comment.page.pageNum': res.data.pageNum,
                    'article.comment.page.pages': res.data.pages,
                })
            }
        })
    },

    // 收起子级评论
    closeSonComment(e) {
        let index = e.currentTarget.dataset.index;
        let showKey = 'article.comment.showSon[' + index + ']'
        this.setData({
            [showKey]: false,
        })
    },


    // 监听评论输入框
    commentValueChange(e) {
        this.setData({
            'article.comment.commentValue': e.detail
        })
    },

    // 给子评论点赞
    agreeCommentSon(e) {
        debugger
        //赞同
        if (!LOGIN.isAuthLogin()) {
            App.$navigateToAuth({ tag: 'mine_push' })
            return;
        }

        let item = e.currentTarget.dataset.item;
        let indexArr = e.currentTarget.dataset.index.split("");
        if (item.isAgree) {
            Toast("已经点赞了");
            return;
        }
        App.$put(true, this.URL.support.replace("?", item.commentNo), {}, res => {
            if (res.R) {
                let key = 'article.comment.list[' + indexArr[0] + '].son[' + indexArr[1] + '].isAgree';
                let keyCount = 'article.comment.list[' + indexArr[0] + '].son[' + indexArr[1] + '].goodCount';
                let countVal = this.data.article.comment.list['' + indexArr[0] + ''].son['' + indexArr[1] + ''].goodCount + 1;
                this.setData({
                    [key]: true,
                    [keyCount]: countVal,
                })
            }
        })
    },

    // 一级评论点赞
    agreeCommentParent(e) {

        //赞同
        if (!LOGIN.isAuthLogin()) {
            App.$navigateToAuth({ tag: 'mine_push' })
            return;
        }

        let item = e.currentTarget.dataset.item;
        let index = e.currentTarget.dataset.index;
        if (item.isAgree) {
            Toast("已经点赞了");
            return;
        }
        App.$put(true, this.URL.support.replace("?", item.commentNo), {}, res => {
            if (res.R) {
                let key = 'article.comment.list[' + index + '].isAgree';
                let countVal = this.data.article.comment.list['' + index + ''].goodCount + 1;
                let keyCount = 'article.comment.list[' + index + '].goodCount';
                this.setData({
                    [key]: true,
                    [keyCount]: countVal,
                })
            }
        })
    },

    // 输入评论内容
    clickCommentSearchInput(e) {
        if (!LOGIN.isAuthLogin()) {
            wx.hideKeyboard()
            // LOGIN.toLogin(res => {
            //     setTimeout(() => {
            //         this.setData({
            //             'showComment': true,
            //             'isAuth': true,
            //             commentInput: true
            //         })
            //     }, 500)
            // })
            this.setData({
                'showComment': false,
            })
            App.$navigateToAuth({ tag: 'mine_push' })
            return;
        }

        this.setData({
            'showComment': true,
            'isAuth': true,
            commentInput: true
        })
    },

    // 点击回复按钮文字
    replyUserClick(e) {
        if (!LOGIN.isAuthLogin()) {
            LOGIN.toLogin(res => {

            })
            return;
        }
        let item = e.currentTarget.dataset.item;
        let index = e.currentTarget.dataset.index;
        let type = e.currentTarget.dataset.type;
        this.setData({
            'article.comment.current': item,
            'article.comment.contentPlaceholder': '回复@' + item.userName + "-" + item.id,
            'article.comment.index': index,
            'article.comment.type': type,
            'article.comment.parentId': type == 'son' ? item.parentId : item.id,
            commentInput: true
        })
    },


    // 提交评论
    submitComment() {
        if (!LOGIN.isAuthLogin()) {
            this.setData({
                'showComment': false
            })
            LOGIN.toLogin(res => {
                setTimeout(() => {
                    this.setData({
                        'showComment': true
                    })
                }, 500)
            })
        }

        if (utils.isInvalid(this.data.article.comment.commentValue)) {
            Toast("请输入内容");
            return;
        }

        // 评论回复对象。 如果评论文章，该对象为空
        let comment = this.data.article.comment.current;


        let params = {
            "articleNo": this.data.article.comment.article.articleNo,
            "content": this.data.article.comment.commentValue
        };
        if (!utils.isInvalid(comment)) {
            // 1.评论用户 回复评论
            params = {
                "replyUserCode": comment.userCode,
                "directParentId": this.data.article.comment.current.id,
                "articleNo": this.data.article.comment.article.articleNo,
                "content": this.data.article.comment.commentValue
            }
        }

        App.$post(true, this.URL.comment, params, res => {
            if (res.R) {
                this.setData({
                    "article.comment.commentValue": '',
                    'article.comment.contentPlaceholder': '留下你的评论吧',
                    'article.comment.current': null, // 还原默认评论文章不回复
                })
                if (!utils.isInvalid(comment)) {
                    // 重新读取一下子评论
                    let search = {
                        'articleNo': this.data.article.comment.article.articleNo,
                        'parentId': this.data.article.comment.parentId
                    }
                    if (this.data.article.comment.type === 'son') {
                        this.reloadSonComment(search, this.data.article.comment.index.split("")[0]);
                    } else {
                        this.reloadSonComment(search, this.data.article.comment.index);
                    }
                }
                // 总数评论加1
                this.setData({
                    'article.comment.allCount': this.data.article.comment.allCount + 1
                })


                // 3.评论文章
                if (utils.isInvalid(comment)) {
                    // 追加当前评论这条数据
                    App.$get(true, this.URL.commentList, { 'articleNo': this.data.article.comment.article.articleNo }, res => {
                        if (res.R) {
                            let list = this.data.article.comment.list
                            list.push(res.data.rows[res.data.rows.length - 1])
                            this.setData({
                                'article.comment.list': list,
                            })
                        }
                    })
                }

                // 列表这条数据评论数+1
                let thisArticle = this.data.article.comment.article
                thisArticle.commentCount = thisArticle.commentCount + 1;
                let thisArticleListKey = 'article.mapTabValue[' + this.data.article.activeKey + '][' + this.data.article.comment.articleIndex + '].commentCount';
                //let thisArticle3 = this.data.article.mapTabValue[this.data.article.activeKey];
                //let thisArticle2 = this.data.article.mapTabValue[this.data.article.activeKey][this.data.article.comment.articleIndex];
                this.setData({
                    [thisArticleListKey]: thisArticle.commentCount
                })
            } else {
                this.setData({
                    'showComment': false
                })
            }
        })
    },

    // 展开子评论
    getCommentSon(e) {
        let item = e.currentTarget.dataset.item;
        let index = e.currentTarget.dataset.index;
        this.reloadCommentSon({ item: item, index: index })
    },

    reloadCommentSon(e) {
        let item = e.item;
        let index = e.index;

        // 展开子评论
        let showKey = 'article.comment.showSon[' + index + ']';
        this.setData({
            [showKey]: true,
            "article.comment.parentId": item.id
        })
        App.$get(true, this.URL.listSon, { 'articleNo': item.articleNo, 'parentId': item.id }, res => {
            if (res.R) {
                let source = this.data.article.comment.list[index];
                source['son'] = res.data
                let key = "article.comment.list[" + index + "]"
                this.setData({
                    [key]: source,
                })
            }
        })
    },


    // 刷新子评论
    reloadSonComment(params, index) {
        let e = {
            'item': { articleNo: params.articleNo, id: params.parentId },
            'index': index
        }
        this.reloadCommentSon(e)
    },

    // 点击文章评论框
    clickCommentInput(e) {
        this.setData({
            'showComment': true,
            'article.comment.article': e.currentTarget.dataset.item, // 当前的文章
            'article.comment.articleIndex': e.currentTarget.dataset.index, // 当前文章所在的序号
            'article.comment.contentPlaceholder': '说点什么',
            'article.comment.current': null, // 还原默认评论文章不回复
        })

        // 展开子评论还原
        for (let i = 0; i < 15; i++) {
            let key = 'article.comment.showSon[' + i + ']'
            this.setData({
                [key]: false
            })
        }
        this.getAllCountNum(e.currentTarget.dataset.item.articleNo);
        this.getCommentList(e.currentTarget.dataset.item.articleNo);
    },

    // 关闭评论弹框
    closeComment() {
        this.setData({
            'showComment': false
        })
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
        if (this.data.article.tabs[this.data.article.activeKey].type === "sameCity") {
            if (!LOCATION.isAllowedLocation()) {
                wx.stopPullDownRefresh();
                return;
            }
        } else if (this.data.article.tabs[this.data.article.activeKey].type === "mine") {
            if (!LOGIN.isAuthLogin()) {
                wx.stopPullDownRefresh();
                return;
            }
        }
        this.init(1, false, this.data.article.activeKey);
    }


    /**
     * 页面上拉触底事件的处理函数
     */
    , onReachBottom: function () {
        if (this.data.page.pages === 0 || this.data.page.pageNum + 1 > this.data.page.pages) {
            this.setLoadingMore(true, "end", "我是有底线的~")
            return;
        }
        this.init(this.data.page.pageNum + 1, true, this.data.article.activeKey);
    },

    setLoadingMore(show, type, text) {
        this.setData({
            "loadMore.show": show,
            "loadMore.type": type,
            "loadMore.text": text,
        })
    }

    ,
    scrollTop() {
        wx.pageScrollTo({
            scrollTop: 0,
        })
    },

    // 页面滚动出发
    onPageScroll(options) {
        let flag = false;
        if (options.scrollTop > 200) {
            flag = true;
        }
        this.setData({
            srcolltop: flag
        })
    },


    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    }
    ,


    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    }
    ,

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    }
    ,
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {
        return App.$onShare(this.page.target, null, "校园CBD")
    },

})
